//
//  CTThirdPartyRegisterLogic.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/4/22.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTThirdPartyRegisterLogic.h"
#import "CTDebugManager.h"
#import "CTUrl.h"
#import "CTRequestUtil.h"
#import "CTHeader.h"
#import "CTFile.h"
#import "CTTextManager.h"

#import "AFHTTPRequestOperationManager.h"
#import "AFSecurityPolicy.h"

@implementation CTThirdPartyRegisterLogic

- (void)dealloc
{
    [CTDebugManager showDebugLogInfo:@"dealloc : CTThirdPartyRegisterLogic Is Removed!!!"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}


-(void)thirdPartyRegisterRequest:(CTUserInfoModifyRequestItem *)item
        successCompletionHandler:(requestSuccessBlock)successBlock
                   failedHandler:(requestFailedBlock)failedBlock

{
    
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithCapacity:0];
    @try {
        
        [param setObject:item.token forKey:@"token"];
        if ([[CTTextManager shareInstance] isBlankString:item.name]==NO)[param setObject:item.name forKey:@"name"];
        if (item.head != nil)[param setObject:item.head forKey:@"head"];
        if ([[CTTextManager shareInstance] isBlankString:item.sign]==NO)[param setObject:item.sign forKey:@"sign"];
        if ([[CTTextManager shareInstance] isBlankString:item.lang]==NO)[param setObject:item.lang forKey:@"lang"];
        if ([[CTTextManager shareInstance] isBlankString:item.gender]==NO)[param setObject:item.gender forKey:@"gender"];
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"组装第三方请求数据失败！！"];
    }
   
    
    
    
    if (item.head == nil) {
        [CTRequestUtil sendAsyPostRequest:CT_URL_USERS_MODIFY(version) withParam:param withCompletionSuccessHandler:^(NSData *data) {
            BOOL isParserSuccess = [self parserData:data];
            if (isParserSuccess == YES) {
                successBlock();
            }
            else
            {
                failedBlock();
            }
        } withFailedHandler:^(NSError *error) {
            failedBlock();
        }];
        
        return;
    }
    
    
    
    
    
    
    
    NSString * url = CT_URL_USERS_MODIFY(version);
    NSError * error;
    if(url == nil){
        [CTDebugManager showErrorLogInfo:@"请求url为空,无法请求!"];
        failedBlock(error);
        return;
    }
    if(param == nil || param.count == 0){
        [CTDebugManager showErrorLogInfo:@"请求参数为空,无法请求!"];
        failedBlock(error);
        return;
    }
    
    //配置url
    NSURL *myURL = [NSURL URLWithString:url];
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:CT_HEADER_REQUEST_TIMEOUT_INTERVAL];
    
    //设置type
    [urlRequest setHTTPMethod:@"POST"];
    
    //设置header
    NSString *contentType = [NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",(NSString *)[param objectForKey:@"token"]]];
    [urlRequest setValue:contentType forHTTPHeaderField:@"token"];
    [param removeObjectForKey:@"token"];
    
    //设置body

    NSMutableData *data = [self parserPostDataForHttpBody:param];
  
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [urlRequest setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [urlRequest setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [urlRequest setHTTPBody:data];
    //http method
    [urlRequest setHTTPMethod:@"POST"];


    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               
                               
                               if( [response isKindOfClass:[NSHTTPURLResponse class]] ){
                                   NSHTTPURLResponse *responseCopy = (NSHTTPURLResponse *)response;
                                   NSInteger statusCode = responseCopy.statusCode;
                                   if(statusCode == 200){
                                       
                                       if (data&&[data length] == 0) {
                                           [CTDebugManager showDebugLogInfo:@"数据为空!!"];
                                           failedBlock();
                                       }
                                       else
                                       {
                                           [CTDebugManager showDebugLogInfo:@"请求成功!!"];
                                          
                                           BOOL isParserSuccess = [self parserData:data];
                                           if (isParserSuccess == YES) {
                                               
                                               successBlock();
                                               
                                               if ([[CTTextManager shareInstance] isBlankString:item.name]==YES && [[CTTextManager shareInstance] isBlankString:item.sign]==YES && [[CTTextManager shareInstance] isBlankString:item.gender]==YES) {
                                                   return ;
                                               }
                                               [CTFile removeFile:@"homepage" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
                                               [CTFile removeFile:@"discovery" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
                                               [CTFile removeFile:@"user" fromDoc:CTFileDocLibrary fromPath:@"cacheData"];
                                               [[NSNotificationCenter defaultCenter] postNotificationName:CTLoginSuccessNotification object:nil];
                                               
                                           }
                                           else
                                           {
                                               
                                               failedBlock();
                                               
                                               if ([[CTTextManager shareInstance] isBlankString:item.name]==YES && [[CTTextManager shareInstance] isBlankString:item.sign]==YES && [[CTTextManager shareInstance] isBlankString:item.gender]==YES) {
                                                   return ;
                                               }
                                               
                                               [[NSNotificationCenter defaultCenter] postNotificationName:CTLoginFailedNotification object:nil];
                                           }
                                           
                                       }
                                   }else{
                                       [CTDebugManager showErrorLogInfo:@"请求失败!!"];
                                       failedBlock();
                                       
                                       if ([[CTTextManager shareInstance] isBlankString:item.name]==YES && [[CTTextManager shareInstance] isBlankString:item.sign]==YES && [[CTTextManager shareInstance] isBlankString:item.gender]==YES) {
                                           return ;
                                       }
                                       
                                       [[NSNotificationCenter defaultCenter] postNotificationName:CTLoginFailedNotification object:nil];
                                   }
                               }
                               
                           }];
}






#pragma mark - data parser -

-(BOOL)parserData:(NSData *)resultData
{
    
    BOOL isParserSuccess = NO;
    
    @try {
        
        NSError * error;
        
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:resultData
                         options:NSJSONReadingAllowFragments
                         error:&error];
        if (jsonObject != nil && error == nil){
            
            if ([jsonObject isKindOfClass:[NSDictionary class]]){
                
                NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
                
                NSString * errCode = [NSString stringWithFormat:@"%@",(NSString *)[deserializedDictionary objectForKey:@"error_code"]];
                if ([errCode isEqualToString:@"0"]) {
                    
                    isParserSuccess = YES;
                  
                    NSDictionary * infoDic = [deserializedDictionary objectForKey:@"info"];
               //     NSDictionary * userInfoDic = [infoDic objectForKey:@"user"];
                 
                    //存入文件
                    
                    //user info
                    [CTFile cacheDicFile:[infoDic mutableCopy]
                                fileName:@"userInfo.plist"
                                 saveDoc:CTFileDocDocuments
                                savePath:@"user"];
                    
                }
            }
        }
        else
        {
            [CTDebugManager showErrorLogInfo:@"解析验证数据错误！"];
        }
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析验证数据错误！"];
    }
    
    return isParserSuccess;
    
}


- (NSMutableData *)parserPostDataForHttpBody:(NSMutableDictionary *)dic
{
    NSMutableData *myRequestData=[NSMutableData data];
    
    NSMutableData * body = [NSMutableData data];
    
    if (dic.count == 0 || dic == nil){
        [CTDebugManager showErrorLogInfo:@"post数据参数为空!!"];
        return body;}
    
    @try {
        //分界线的标识符
        NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
        //分界线 --AaB03x
        NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
        //结束符 AaB03x--
        NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
        //要上传的图片
  //      UIImage *image=(UIImage *)[dic objectForKey:@"head"];
        //得到图片的data
        //        NSData* data = UIImagePNGRepresentation(image);
        NSData *data = [dic objectForKey:@"head"];
//        UIImageJPEGRepresentation(image, 1.0f);
        //        NSString *_encodedImageStr = [data base64Encoding];
        
        //http body的字符串
        NSMutableString *body=[[NSMutableString alloc]init];
        //参数的集合的所有key的集合
        NSArray *keys= [dic allKeys];
        
        //遍历keys
        for(int i=0;i<[keys count];i++)
        {
            //得到当前key
            NSString *key=[keys objectAtIndex:i];
            //如果key不是pic，说明value是字符类型，比如name：Boris
            if(![key isEqualToString:@"head"])
            {
                //添加分界线，换行
                [body appendFormat:@"%@\r\n",MPboundary];
                //添加字段名称，换2行
                [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
                //添加字段的值
                [body appendFormat:@"%@\r\n",[dic objectForKey:key]];
            }
        }
        
        ////添加分界线，换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //声明pic字段，文件名为boris.png
        [body appendFormat:@"Content-Disposition: form-data; name=\"head\"; filename=\"boris.png\"\r\n"];
        //声明上传文件的格式
        [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
        
        //声明结束符：--AaB03x--
        NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
        
        //将body字符串转化为UTF8格式的二进制
        [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
        //将image的data加入
        [myRequestData appendData:data];
        //加入结束符--AaB03x--
        [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
        
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"组装发布Body数据失败!!"];
    }
    
    
    return myRequestData;

}




@end
